import DB from '../models/db.js';

/**
 * API认证中间件
 * 验证请求头中的API Key和Secret
 */
export const apiAuth = async (req, res, next) => {
    try {
        // 从请求头中获取认证信息
        const authHeader = req.headers.authorization;
        
        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            return res.status(401).json({
                success: false,
                message: '未提供API认证信息'
            });
        }

        // 解析Bearer Token
        const token = authHeader.split(' ')[1];
        const [apiKey, apiSecret] = token.split(':');

        if (!apiKey || !apiSecret) {
            return res.status(401).json({
                success: false,
                message: 'API认证信息格式错误'
            });
        }

        // 查询并验证API密钥
        const apiKeyRecord = await DB.ApiKeys.findOne({
            where: { 
                api_key: apiKey,
                api_secret: apiSecret,
                status: 'active'
            },
            include: [{
                model: DB.EmployerApplications,
                as: 'employer',
                attributes: ['application_id', 'company_name', 'application_status'],
                required: true
            }]
        });

        if (!apiKeyRecord) {
            return res.status(401).json({
                success: false,
                message: '无效的API认证信息'
            });
        }

        // 检查关联的雇主申请状态
        if (apiKeyRecord.employer.application_status !== 'approved') {
            return res.status(403).json({
                success: false,
                message: '雇主申请未通过审核'
            });
        }

        // 更新最后使用时间
        await apiKeyRecord.update({
            last_used_at: new Date()
        });

        // 将API密钥信息添加到请求对象中
        req.apiKey = apiKeyRecord;
        req.employer = apiKeyRecord.employer;

        next();
    } catch (error) {
        console.error('API认证错误:', error);
        return res.status(500).json({
            success: false,
            message: 'API认证过程发生错误'
        });
    }
};

/**
 * 可选的API认证中间件
 * 如果提供了认证信息则验证，否则允许继续
 */
export const optionalApiAuth = async (req, res, next) => {
    try {
        const authHeader = req.headers.authorization;
        
        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            return next();
        }

        const token = authHeader.split(' ')[1];
        const [apiKey, apiSecret] = token.split(':');

        if (!apiKey || !apiSecret) {
            return next();
        }

        const apiKeyRecord = await DB.ApiKeys.findOne({
            where: { 
                api_key: apiKey,
                api_secret: apiSecret,
                status: 'active'
            },
            include: [{
                model: DB.EmployerApplications,
                as: 'employer',
                attributes: ['application_id', 'company_name', 'application_status'],
                required: true
            }]
        });

        if (apiKeyRecord && apiKeyRecord.employer.application_status === 'approved') {
            await apiKeyRecord.update({
                last_used_at: new Date()
            });
            req.apiKey = apiKeyRecord;
            req.employer = apiKeyRecord.employer;
        }

        next();
    } catch (error) {
        console.error('可选API认证错误:', error);
        next();
    }
}; 